import React from 'react'
import { Cascader } from 'antd';
import api from '../../../api/communityManage';
import equal from 'deep-equal';

import './index.less'

export default class CommunityCascader extends React.Component {
  constructor(props) {
    super(props);
    let defaultValue = [];
    defaultValue.push(props.value || props.defaultValue);
    this.state = {
      main: {
        defaultValue,
        isChange: false,
        data: [],
        loading: false
      }
    };
  }

  componentWillReceiveProps = (nextProps) => {
    if (this.props.defaultValue == undefined && nextProps.defaultValue != this.props.defaultValue) {
      let pid = nextProps.pid;
      let max = nextProps.maxLevel || this.main.props.maxLevel;
      let defaultValue = nextProps.defaultValue;
      this.main.initData(pid, max, defaultValue || null);
    }
    /*if (nextProps.value == undefined && this.props.value != undefined) {
      this.main.setMainState("defaultValue", []);
    }
    if (nextProps.pid != undefined && nextProps.pid != this.props.pid) {
      let pid = nextProps.pid;
      let max = nextProps.maxLevel || this.main.props.maxLevel;
      let defaultValue = nextProps.value;
      this.main.initData(pid, max, defaultValue || null);
    }
    if (this.state.main.isChange && nextProps.value != undefined && "data-__meta" in nextProps && nextProps.value == nextProps["data-__meta"].initialValue && typeof nextProps.value == 'string') {
      this.main.setMainState("isChange", false);
      let pid = nextProps.pid;
      let max = nextProps.maxLevel || this.main.props.maxLevel;
      let defaultValue = nextProps.value;
      this.main.initData(pid, max, defaultValue || null);
    }*/
    if (!(nextProps.value instanceof Array) && nextProps.value != this.props.value) {
      let pid = nextProps.pid;
      let max = nextProps.maxLevel || this.main.props.maxLevel;
      let defaultValue = nextProps.value;
      this.main.initData(pid, max, defaultValue || null, false);
    }
  }

  componentDidMount = () => {
    let pid = this.main.props.pid;
    let max = this.main.props.maxLevel;
    let defaultValue = this.state.main.defaultValue;
    this.main.initData(pid, max, defaultValue.length > 0 && defaultValue[0]);
  }

  componentWillMount = () => {
    this._isMounted = true;
  }
  componentWillUnmount() {
    this._isMounted = false
  }

  main = {
    props: {
      className: this.props.className,
      style: this.props.style,
      size: this.props.size,
      disabled: this.props.disabled,
      placeholder: this.props.placeholder || "请选择一个位置",
      showSearch: this.props.showSearch == undefined ? true : this.props.showSearch,
      changeOnSelect: this.props.changeOnSelect == undefined ? true : this.props.changeOnSelect,
      notFoundContent: this.props.notFoundContent || "未找到内容",
      pid: this.props.pid, //顶级父类id
      defaultValue: this.props.defaultValue || "", //默认值 区域id 类型string
      maxLevel: this.props.maxLevel || 6, //显示和选择的最大等级,默认6
      onChange: (values) => { //选择改变事件,与form组件实现集成
        this.props.onChange && this.props.onChange(values);
      }
    },
    initData: (pid, max, defaultValue, isChange = true) => {
      let index = 0;
      let getCommunityArray = () => {
        return new Promise((resolve, reject) => {
          let promise = [this.main.getCommunityStructure(defaultValue)];
          if (pid != undefined) {
            promise.push(this.main.getCommunityStructure(pid, this.props.office));
          }
          Promise.all(promise).then(([array, i]) => {
            if (i && i.length > 0) {
              index = i.length;
              for (let m = 0; m < index; m++) {
                if (array.length > 0) {
                  array.shift();
                }
              }
            }
            resolve(array);
          }).catch(e => {
            reject(e);
          });
        });
      }
      getCommunityArray().then(arr => {
        defaultValue = arr;
        this.main.setMainState("defaultValue", arr);
        defaultValue.length = Math.min(defaultValue.length, max);
        return this.main.selectList[index](pid, max == 1);
      }).then(first => {
        let promise = [];
        for (let i = 0; i < defaultValue.length - 1; i++) {
          let isLeaf = false;
          let selectedId = defaultValue[i];
          promise.push(this.main.selectList[index + i + 1](selectedId, i + 2 >= max));
        }
        Promise.all(promise).then(result => {
          let current = first;
          for (let m = 0; m < defaultValue.length; m++) {
            let selected = defaultValue[m];
            for (let n = 0; n < current.length; n++) {
              let element = current[n];
              if (element.value == selected) {
                element.children = result[m];
                current = result[m];
                break;
              }
            }
          }
          this.main.setMainState("data", first);
          isChange && defaultValue && defaultValue.length > 0 && this.main.onChange(defaultValue);
        });
      });
    },
    onChange: (values, selectedOptions) => {
      this.main.setMainState("isChange", true);
      this.main.setMainState("defaultValue", values);
      this.main.props.onChange && this.main.props.onChange([...values]);
    },
    loadData: (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      targetOption.children = [];
      let nextIsLeaf = false;
      if (selectedOptions.length == this.main.props.maxLevel - 1) {
        nextIsLeaf = true;
      }
      this.main.selectList[targetOption.level + 1](targetOption.value, nextIsLeaf).then(array => {
        targetOption.children = array;
        targetOption.loading = false;
        this.main.setMainState("data", this.state.main.data);
      });
    },
    setMainState: (key, value) => {
      let main = this.state.main;
      main[key] = value;
      this._isMounted && this.setState({
        main
      });
    },
    selectList: [(pid, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/api/sysOffice', { parent_id: pid, type: '1,2,4' }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 0,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    }), (pid = 1, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/api/office/child', { officePId: pid, type: 3 }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 1,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    }), (pid = 1, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/community/getCommunity', { office_id: pid }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 2,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    }), (pid = 1, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/community/getBuild', { infoId: pid }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 3,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    }), (pid = 1, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/community/getFloor', { buildId: pid }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 4,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    }), (pid = 1, isLeaf = false) => new Promise((resolve, reject) => {
      api.get('/community/room', { floorId: pid }).then(res => {
        const result = res.data || [];
        let array = [];
        for (let i = 0; i < result.length; i++) {
          array.push({
            value: result[i].id,
            level: 5,
            label: result[i].name,
            isLeaf
          });
        }
        resolve(array);
      });
    })],
    getCommunityStructure: (id,office) => new Promise((resolve, reject) => {
      if (id == undefined) {
        resolve([]);
        return;
      }
      api.get('/community/parents', { id }).then(data => {
        if(office){
          if(data && data.length > 0){
            data.shift();
          }
        }
        resolve(data);
      });
    })
  }

  render() {
    return (
      <Cascader
        options={this.state.main.data}
        showSearch={this.props.showSearch == undefined ? true : this.props.showSearch}
        loadData={this.main.loadData}
        onChange={this.main.onChange}
        style={this.props.style}
        size={this.props.size}
        disabled={this.props.disabled}
        className={this.props.className}
        value={this.state.main.defaultValue}
        placeholder={this.props.placeholder || "请选择一个位置"}
        notFoundContent={this.props.notFoundContent || "未找到内容"}
        changeOnSelect={this.props.changeOnSelect == undefined ? true : this.props.changeOnSelect}
      />
    );
  }
}